<?php

namespace app\admin\model\course;

use addons\epay\library\Service;
use app\admin\model\user\Student;
use app\common\model\MoneyLog;
use app\common\model\User;
use think\Db;
use think\Model;
use app\common\model\order\PayLog;


class Order extends Model
{

    // 表名
    protected $name = 'course_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_time_text',
        'complete_time_text'
    ];



    const TYPE_COURSE = 1;// 普通订单
    const TYPE_SPELL = 2;// 拼团订单
    const TYPE_ADMIN = 3;// 后台录单
    const TYPE_RESTORE = 4;// 恢复上课
    const TYPE_TRANSFER = 5;// 转单
    public function getTypeList(){
        return [
            self::TYPE_COURSE => __("普通订单"),
            self::TYPE_SPELL => __("拼团订单"),
            self::TYPE_ADMIN => __("后台录单"),
            self::TYPE_RESTORE => __("恢复订单"),
            self::TYPE_TRANSFER => __("转单"),
        ];
    }
    public function getTypeText($type){
        $list = self::getTypeList();
        if(isset($list[$type])){
            $res = $list[$type];
            return  $res;
        }else{
            return "未知";
        }
    }

    public static function getInStatusArr(){
        return [
            self::STATUS_PAY,
            self::STATUS_UN_TEACHER,
            self::STATUS_TEACHER,
        ];
    }
    //状态
    const STATUS_REFUND = -100; // 退款
    const STATUS_STOP = -2; // 已停课
    const STATUS_CANCEL = -1; // 已取消
    const STATUS_UN_PAY = 10; // 待支付
    const STATUS_PAY = 20; // 已支付
    const STATUS_UN_TEACHER = 21; // 未排课
    const STATUS_TEACHER = 22; // 已排课
    const STATUS_SUCCESS = 100; // 已完成
    public function getStatusList(){
        return [
            self::STATUS_PAY => __("已支付"),
            self::STATUS_UN_PAY => __("待支付"),
            self::STATUS_SUCCESS => __("已完成"),
            self::STATUS_REFUND => __("已退款"),
            self::STATUS_CANCEL => __("取消"),
            self::STATUS_STOP => __("已停课"),
            self::STATUS_UN_TEACHER => __("未排课"),
            self::STATUS_TEACHER => __("已排课"),
        ];
    }
    public function getStatusText($status){
        $list = self::getStatusList();
        if(isset($list[$status])){
//            //如果是退换货的 添加退换货状态
            $res = $list[$status];
            return  $res;
        }else{
            return "未知";
        }
    }
    //平台
    const PAY_FROM_MINIAPP = "miniapp";
    const PAY_FROM_ADMIN = "admin";
//    const PAY_FROM_APP = "app";
    public function getPayFromList(){
        return [
            self::PAY_FROM_MINIAPP => "微信小程序",
            self::PAY_FROM_ADMIN => "后台录单",
//            self::PAY_FROM_APP => "App",
        ];
    }
    public function getPayFromText($pay_from){

        $list = self::getPayFromList();
        if(isset($list[$pay_from])){
            return  $list[$pay_from];
        }else{
            return "未知";
        }
    }

    //支付方式
    const PAY_TYPE_WECHAT = "wechat";
    const PAY_TYPE_ALIPAY = "alipay";
    const PAY_TYPE_MONEY = "money";
    const PAY_TYPE_ADMIN = "admin";
    public function getPayTypeList(){
        return [
            self::PAY_TYPE_WECHAT => "微信",
            self::PAY_TYPE_ALIPAY => "支付宝",
            self::PAY_TYPE_MONEY => "余额",
            self::PAY_TYPE_ADMIN => "后台录单",
        ];
    }
    public function getPayTypeText($pay_type){
        $list = self::getPayTypeList();
        if(isset($list[$pay_type])){
            return  $list[$pay_type];
        }else{
            return "未知";
        }
    }

    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }





    public function getCompleteTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['complete_time']) ? $data['complete_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    protected function setCompleteTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function payUser()
    {
        return $this->belongsTo('app\common\model\User', 'pay_user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function course()
    {
        return $this->belongsTo('app\admin\model\course\Course', 'course_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function orderGoods()
    {
        return $this->hasMany('orderGoods','order_id', 'id');
    }


    /*
     * 获取订单列表
     * */
    public function getOrderList($condition = [],$is_paginate = 1)
    {
        $list = self::with(['orderGoods'=>function($query){
            $query->withField(['id', 'order_id','course_name', 'image','school_name','classes_name','w_name','time_name','teacher_id']);
        },'course'=>function($query){
            $query->withField(['id','name', 'image','class_hour','desc']);
        }])->where($condition)->order("order.id","desc");

        if($is_paginate == 1){
            $list = $list->paginate();
        }else{
            $list = $list->select();
        }
        $userModel = new User();
        foreach ($list as $key => &$value){
            $value["status_text"] = $this->getStatusText($value["status"]);
            if($value['course']['image']){
                $value['course']['image'] = deal_img_url($value['course']['image']);
            }
//
            $value["teacher_name"] = "";
            foreach ($value['order_goods'] as $goodsKey => $goodsValue){
                $teacher = $userModel->getTeacherInfo(['id'=>$goodsValue['teacher_id']]);
                $goodsValue['teacher'] = $teacher;
                $teacher_name = $teacher['nickname']??'';
                $goodsValue['image'] = deal_img_url($goodsValue['image']);
                $value["teacher_name"] = ($goodsKey > 0)?$value["teacher_name"]."|".$teacher_name:$value["teacher_name"]."".$teacher_name;
                $goodsValue['xiaojie_image_arr'] = [];
                if($goodsValue['xiaojie_image']){
                    $goodsValue['xiaojie_image_arr'] = explode(",",$goodsValue['xiaojie_image']);
                }
            }
            $value = $this->dealOrderInfo($value);
        }
        return $list;
    }
    /*
     * 获取订单详情
     * */
    public function getOrderInfo($condition = []){
        $res = self::with(['course'=>function($query){
            $query->withField(['id','name', 'image','class_hour','desc']);
        },'orderGoods'=>function($query){
            $query->withField(['id', 'order_id','course_name', 'image','school_name','classes_name','w_name','time_name']);
        },'user'=>function($query){
            $query->withField(['id', 'nickname','avatar']);
        },'pay_user'=>function($query){
            $query->withField(['id', 'nickname','avatar']);
        }])->where($condition)->find();
        if($res){
            $res["pay_type_text"] = $this->getPayTypeText($res["pay_type"]);
            $res['cancel_time_text'] = "";

            if($res['course']['image']){
                $res['course']['image'] = deal_img_url($res['course']['image']);
            }
            if($res['status'] == self::STATUS_UN_PAY){
                //取消时间
                $cancel_time = config('site.cancel_time')??15;
                $endTime = $res['createtime'] + ($cancel_time*60);
                if(time() > $endTime){
                    $order = $this->where("id",$res['id'])->find();
                    $order->cancelOrder("订单超时取消");
                    $res['status'] = self::STATUS_CANCEL;
                }
                $res['cancel_time_text'] = date("Y-m-d H:i:s",$endTime);
            }
            $res["status_text"] = $this->getStatusText($res["status"]);
            $res["teacher_name"] = "";

            $userModel = new User();
            foreach ($res['order_goods'] as $goodsKey => $goodsValue){
                $teacher = $userModel->getTeacherInfo(['id'=>$goodsValue['teacher_id']]);
                $goodsValue['teacher'] = $teacher;
                $teacher_name = $teacher['nickname']??'';
                $res["teacher_name"] = ($goodsKey > 0)?$res["teacher_name"]."|".$teacher_name:$res["teacher_name"]."".$teacher_name;
            }
            $res = $this->dealOrderInfo($res);
        }else{
            exception("未找到当前订单");
        }


        return $res;
    }

    public function dealOrderInfo($info){
        //剩余课时
        $info['surplus_class_hour'] = 0;
        if(isset($info['class_hour']) && isset($info['order_goods'])){
            $use_class_hour = 0;
            foreach ($info['order_goods'] as $orderGoodsKey => $orderGoods){
                $use_class_hour += OrderSign::where([
                    "order_id" => $orderGoods['order_id'],
                    "student_id" => $orderGoods['student_id'],
                    "course_id" => $orderGoods['course_id'],
                    "school_id" => $orderGoods['school_id'],
                    "classes_id" => $orderGoods['classes_id'],
                    "time_no" => $orderGoods['time_no'],
                    "w" => $orderGoods['w'],
                ])->where(function($query){
                    $query->where(function ($query1) {
                        $query1->where([
                            "status" => ['in',[OrderSign::STATUS_SIGN,OrderSign::STATUS_ADMIN_SIGN,OrderSign::STATUS_ACTIVITY,OrderSign::STATUS_ADMIN]],
                        ]);
                    })->whereOr(function ($query2)  {
                        $query2->where([
                            "status"=>OrderSign::STATUS_LEAVE,
                            "is_buke"=>1,
                        ]);
                    });
                })->sum("class_hour");
                $xiaojie_image_arr = array_filter(explode(",",$orderGoods['xiaojie_image']));
                $orderGoods['xiaojie_image_arr'] = $xiaojie_image_arr;
            }
//            if()


            $info['surplus_class_hour'] = ($info['class_hour']-$use_class_hour > 0 )?($info['class_hour']-$use_class_hour):0;
            if($info['class_hour'] == 0){
                $info['surplus_price'] = 0;
            }else{
                $info['surplus_price'] = bcmul($info['money'],bcdiv($info['surplus_class_hour'],$info['class_hour'],2),2);
            }

//            $info['']

        }
        $info['class_hour_tip'] = config("site.class_hour_tip")??5;
        return $info;
    }

    /*
     * 创建订单
     * */
    public function createOrder($user,$data,$time_arr,$coupon_id = 0,$admin_msg = ""){
        if($user == null){
            exception("未找到当前用户");
        }
        if(count($time_arr) == 0 ){
            exception("请选择班次");
        }
//        dump($coupon_id);exit;
        $courseModel = new \app\admin\model\course\Course();
        //判断 校区,班次,时间段是否正确，并且有没有名额
        $data["spell_id"] = 0;
        switch ($data['type']){
            case self::TYPE_COURSE:
            case self::TYPE_ADMIN:
            case self::TYPE_RESTORE:
            case self::TYPE_TRANSFER:
                $course = $courseModel->getInfo(["id"=>$data['data_id']]);
                break;
            case self::TYPE_SPELL:
                $spellModel = new Spell();
                $spell = $spellModel->getInfo(["id"=>$data['data_id']]);
                $course = $spell['course'];
                $data["spell_id"] = $spell['id'];
                break;
        }


//        dump($course);exit;


//        return $course;


        $checkRes = $this->checkOrder($time_arr,$course,$data,$user);

        $fee = $courseModel->preOrder($data['type'], $data['data_id'], $coupon_id,$user['id'],$data['pay_type']);
//        dump($fee);exit;
        //创建订单
        $order_sn = PayLog::getOrderSn(PayLog::COURSE_ORDER);
        $data = [
            "user_id"=>$user["id"],
            "order_sn" =>$order_sn,
            "status" => self::STATUS_UN_PAY,
            "money" => $fee['money'],
            "course_id" => $course['id'],
            "course_price" => $fee['price'],
            "discount_money" => $fee['discount_money'],
            "vip_discount_money" => $fee['vip_discount_money'],
            "student_id" => $data['student_id'],
            "student_name" => $checkRes["student"]['name'],
            "parent_name" => $data['parent_name'],
            "phone_1" => $data['phone_1']??'',
            "phone_2" => $data['phone_2']??'',
            "phone_3" => $data['phone_3']??'',
            "school_id" => $data['school_id'],
            "school_name" => $checkRes['school_name'],
            "classes_id" => $data['classes_id'],
            "classes_name" => $checkRes['classes_name'],
            "coupon_id" => $coupon_id,
            "type" => $data['type'],
            "spell_id" => $data['spell_id'],
            "class_hour" => $course['class_hour'],
            "team_id" => $checkRes['team_id']??0,
            "is_leader" => $checkRes['is_leader']??0,
//            "remark" => $remark,
        ];

        $this->save($data);
        $orderGoodsModel = new OrderGoods();
        //创建子订单orderGoods
//        dump($time_arr_end);exit;
        $orderGoodsData = [];
//        dump($checkRes['time_arr_end']);exit;
        foreach ($checkRes['time_arr_end'] as $key => $value){
            $orderGoodsData[] = [
                "order_id" => $this->id,
                "user_id" => $user["id"],
                "course_name" => $course["name"],
                "status" => self::STATUS_UN_PAY,
                "image" => $course['image'],
                "course_id" => $course['id'],
                "school_id" => $value['school_id'],
                "school_name" => $value['school_name'],
                "classes_id" => $value['classes_id'],
                "classes_name" => $value['classes_name'],
                "time_no" => $value['time_no'],
                "time_name" => $value['time_name'],
                "w" => $value['w'],
                "w_name" => $value['w_name'],
                "teacher_id" => $value['teacher_id'],
                "type" => $data['type'],
                "spell_id" => $data['spell_id'],
                "student_id" => $data['student_id'],
                "student_name" => $checkRes["student"]['name'],
                "class_hour" => $value["class_hour"],
                "createtime" => time(),
                "updatetime" => time(),
                "start_time" => strtotime($value['time_start']) - strtotime(date("Y-m-d")),//推送时间
                "push_day" => "2000-01-01"
            ];


        }
        $orderGoodsModel->insertAll($orderGoodsData);
        //添加日志
        $orderLog = new OrderLog();
        $logData = [
            "order_id" => $this->id,
            "user_id" => $user["id"],
            "content" => $admin_msg==""?"创建订单":$admin_msg
        ];
        $orderLog->save($logData);
//        //设置优惠券为取消
        if ($coupon_id > 0) {
            $coupon = UserCoupon::get($coupon_id);
            $coupon->status = Coupon::STATUS_USE;
            $coupon->save();
        }

        return ["order_id"=> $this->id, "order_sn"=>$this->order_sn,"spell_id" => $this->spell_id];

    }

    /*
     * 检测订单
     * */

    public function checkOrder($time_arr,$course,$data, $user){
//        dump($time_arr);
//        dump($data);
//        exit;

        $time_no_arr = [];
        $time_no_arr_end = [];
        //最终时间段数组
        $time_arr_end = [];

        foreach ($time_arr as $timeKey => $timeValue){
            $time_no_arr[] = $data['school_id']."_".$data['classes_id']."_".$timeValue['w']."_".$timeValue['time_no'];
        }
//        dump($time_no_arr);exit;
        $school_id = 0;
        $classes_id = 0;
        $select_count = 0;
        $school_name = "";
        $classes_name = "";
//        dump($course['config']);
//        exit;
        foreach ($course['config'] as $schoolKey => $schoolValue){
            if($data['school_id'] == $schoolValue["school_id"]){
                $school_id = $schoolValue["school_id"];
                $school_name = $schoolValue["school_name"];
            }
            foreach ($schoolValue['data'] as $classesKey=>$classesValue){
                if($data['classes_id'] == $classesValue["classes_id"]){
                    $classes_id = $classesValue["classes_id"];
                    $classes_name = $classesValue['classes_name'];
                    $select_count = $classesValue["select_count"];
                }
                foreach ($classesValue['data'] as $dayKey => $dayValue){
//                    if(in_array($dayValue['w'],$w_arr)){
//                        $w_arr_end[] = $dayValue['w'];
//                    }

                    foreach ($dayValue['config'] as $timeKey => $timeValue){
                        if(in_array($schoolValue["school_id"]."_".$classesValue["classes_id"]."_".$dayValue['w']."_".$timeValue['time_no'],$time_no_arr)){
                            $time_no_arr_end[] = $schoolValue["school_id"]."_".$classesValue["classes_id"]."_".$dayValue['w']."_".$timeValue['time_no'];
                            $teacher = User::where("id",$timeValue['teacher_id'])
                                ->where("user_type",2)
                                ->find();
                            if(!$teacher){
//                                exception($dayValue['name']." ".$timeValue['start']."-".$timeValue['end']."时间段未配置授课老师，无法下单");
                            }
                            $time_arr_end[] = [
                                "school_id" => $schoolValue['school_id'],
                                "school_name" => $schoolValue['school_name'],
                                "classes_id" => $classesValue['classes_id'],
                                "classes_name" => $classesValue['classes_name'],
                                "w" => $dayValue['w'],
                                "w_name" => $dayValue['name'],
                                "time_no" => $timeValue['time_no'],
                                "time_name" => $dayValue['name']." ".$timeValue['start']."-".$timeValue['end'],
                                "teacher_id" => $timeValue['teacher_id'] == ""?0:$timeValue['teacher_id'],
                                "class_hour" => $timeValue['count'],
                                "time_start" => $timeValue['start'],
                                "time_end" => $timeValue['end'],
                            ];
                            // todo 判断是否还有人数
                            if($timeValue['student_num'] <= $timeValue['buy_num'] && $data['type'] != Order::TYPE_ADMIN){
                                exception($dayValue['name']." ".$timeValue['start']."-".$timeValue['end']."时间段人员已满，无法下单");
                            }
                        }
                    }
                }
            }
        }
//        dump($time_arr_end);exit;

        $time_no_diff = array_diff($time_no_arr,$time_no_arr_end);

//        dump($w_diff);
//        dump($time_no_arr);
//        dump($time_no_arr_end);
//        dump($time_no_diff);
//        dump($time_arr_end);
//        exit;


        if($school_id == 0){
            exception("未找到当前校区");
        }
        if($classes_id == 0){
            exception("未找到当前班次");
        }

        if((count($time_arr) != $select_count) || $select_count == 0){
            exception("请选择{$select_count}个时间段");
        }


        if(count($time_no_diff) > 0){
            exception("请选择正确的时间段");
        }

        //检测学员是否正确
        $student = Student::where("id",$data['student_id'])
            ->find();
        if(!$student){
            exception("请选择学员");
        }
        //如果是拼团订单 检测下拼团人数是否已满
        $team_id = $data['team_id']??0;
        $is_leader = 0;
        if($data['type'] == self::TYPE_SPELL){
            $spellModel = new Spell();
            //检测拼团
            $spellModel->spellUserNum($data['spell_id'],$course['id'],$team_id,2);
            if($team_id == 0){ //没有团队 自己成团当团长
                $is_leader = 1;
            }
        }
        //判断当前订单是否已经支付
        if(isset($data['id']) && $data['status'] != self::STATUS_UN_PAY){
            exception("当前订单状态错误");
        }

        //判断当前学员 是否已经报名了当前课程
        $studentCourseCount = OrderGoods::where([
            "student_id" => $data['student_id'],
            "status" => self::STATUS_PAY,
//            "w" => $data['w'],
//            "time_no" => $data['time_no'],
            "course_id" => $course['id']
        ])->count();
        if($studentCourseCount > 0){
            if (count($time_arr_end) > 0){
                foreach ($time_arr_end as $key => $tValue){
                    $tCount = OrderGoods::where([
                        "student_id" => $data['student_id'],
                        "status" => self::STATUS_PAY,
                        "w" => $tValue['w'],
                        "time_no" => $tValue['time_no'],
                        "course_id" => $course['id']
                    ])->count();
                    if($tCount  > 0){
                        //判断是否是同一个时间段
                        exception("当前学员已报名过该课程的：".$tValue['time_name']);
                    }
                }
            }

        }



        return [
            "school_id" => $school_id,
            "student" => $student,
            "school_name" => $school_name,
            "classes_name" => $classes_name,
            "time_arr_end" => $time_arr_end,
            "team_id" => $team_id,
            "is_leader" => $is_leader,
        ];
    }


    /*
     * 支付订单
     * */
    public function payOrder($user, $pay_from, $pay_type){
        if($this->status != self::STATUS_UN_PAY){
            exception("订单状态错误");
        }
        if($pay_type == "money"){
            //如果是余额支付先扣除余额
            \app\admin\model\User::money(-abs($this->money), $user["id"], MoneyLog::MONEY, MoneyLog::SHOP_FROM_TYPE, "支付订单" . $this->order_sn);
        }
        if($user['id'] != $this['user_id']){
            $this->is_other_pay = 1;
            $this->pay_user_id = $user['id'];
        }
        $this->status = self::STATUS_PAY;
        $this->pay_from = $pay_from;
        $this->pay_type = $pay_type;
        $this->pay_time = time();


        //拼团订单 如果满了 设置 团长状态
        if($this['type'] == $this::TYPE_SPELL){
            //如果是团长的拼团订单  加有效时间
            $spellModel = new Spell();
            $spellInfo = $spellModel->getInfo(["id"=>$this['spell_id']],null,'',"",false);
            if($spellInfo){
                if($this['team_id'] == 0 && $this['is_leader'] == 1){
                    $this->residue_time = time()+($spellInfo['team_time']*60);
                }
                //判断团长的拼团是否完成
                if($this['team_id'] > 0){
                    $this->residue_time = Order::where("id",$this['team_id'])->value("residue_time")??0;
                    $team_user_count = $spellModel->getSpellTeamUserNum($this['team_id']) + 1;
                    if($team_user_count>=$spellInfo['user_num']){
                        Order::where("id",$this['team_id'])->update(['team_status' => 1]);
                        Order::where("team_id",$this['team_id'])->update(['team_status' => 1]);
                    }
                }
            }



        }

        $this->save();

        OrderGoods::where("order_id",$this["id"])->update([
            "status" => self::STATUS_PAY
        ]);
        //添加日志
        $logMsg = "支付订单";
        if($pay_type == "admin"){
            $logMsg = "后台录单，默认自动支付";
        }
        $orderLog = new OrderLog();
        $logData = [
            "order_id" => $this->id,
            "user_id" => $user["id"],
            "content" => $logMsg
        ];
        $orderLog->save($logData);
        //给用户打标签
        $courseModel = new \app\admin\model\course\Course();
        $course = $courseModel->getInfo(["id"=>$this['course_id']]);
        $tagArr = array_filter(explode(",",$course['tags']));
        $userTagArr = array_filter(explode(",",$user['tags']));
        $userTag = array_unique(array_merge($tagArr,$userTagArr));
        $user->save([
            "tags" => implode(",",$userTag)
        ]);
        //发积分
        $money_change_integral = config("site.money_change_integral")??1;
        $integral = abs(bcmul($this["money"] , $money_change_integral,2));
        \app\admin\model\User::money($integral, $this['user_id'] , MoneyLog::SCORE , MoneyLog::BUY_COURSE_INTEGRAL, "购买课程送积分");


    }


    /*
     * 任务定时取消订单
     * 默认一个小时定时取消
     * */
    public function timingCancelOrder(){
        $cancel_time = config('site.cancel_time')??15;
        $endTime = time() - ($cancel_time*60);
        self::where("status", self::STATUS_UN_PAY)
            ->where("createtime", "<=", $endTime)
            ->chunk(100,function ($orders) {
                foreach($orders as $order){
                    $order->cancelOrder("订单超时取消");
                }
            });
    }
    /*
     * 取消订单
     * */
    public function cancelOrder($msg = ""){



        if(!in_array($this->status, [self::STATUS_UN_PAY,$this::STATUS_STOP])){
            exception("当前状态不允许取消");
        }

        //停课的不需要退优惠券
        if ($this['coupon_id'] > 0 && in_array($this->status, [self::STATUS_UN_PAY])) {
            $coupon = UserCoupon::get($this['coupon_id']);
            $coupon->status = Coupon::STATUS_SEND;
            $coupon->save();
        }
        $this->status = self::STATUS_CANCEL;
        $this->save();
        //添加日志
        $orderLog = new OrderLog();
        $msg = $msg ?: "取消订单";
        $logData = [
            "order_id" => $this->id,
//            "user_id" => $user["id"],
            "content" => $msg,
        ];



        $orderLog->save($logData);
    }

    /*
     * 退款
     * */
    public function refundOrder($user, $msg = "", $refund_content = "",$refund_money = 0){
        if(!in_array($this->status, [ self::STATUS_PAY])){
            exception("当前状态不允许取消");
        }
        $this->refund($user,$refund_content,$refund_money);


        //添加日志
        $orderLog = new OrderLog();
        $msg = $msg ?: "退款订单";
        $logData = [
            "order_id" => $this->id,
//            "user_id" => $user["id"],
            "content" => $msg,
        ];

        $orderLog->save($logData);
    }

    //退款操作
    private function refund($user,$refund_content='',$refund_money = 0){
        if($refund_money > $this["money"]){
            exception("当前订单总金额为：".$this['money']);
        }
        $this->refund_content = $refund_content;
        //后台录单的无法退款 是 取消
        switch ($this->pay_type){
            //
            case "admin":
                $this->status = self::STATUS_CANCEL;
                $this->save();
                break;
            case "money":
                //如果是余额支付 退回余额
                \app\admin\model\User::money(abs($this->money), $user["id"], MoneyLog::MONEY, MoneyLog::SHOP_CANCEL_FROM_TYPE, "商城退款" . $this->order_sn);
                $this->status = self::STATUS_REFUND;
                $this->save();

                break;
            case "wechat":
                $payLog = PayLog::where("order_sn", $this["order_sn"])->find();
                $refund_fee = $refund_money>0?$refund_money:$this["money"];
                $payLog->changeRefundNo();
                $params = [
                    'type'         => self::PAY_TYPE_WECHAT,
                    'orderid' => $this["order_sn"],
                    'out_refund_no' => $payLog["refund_no"],
                    'title'        => "商城退款",
                    'amount'       => $this["money"],
                    'refund_fee'       => $refund_fee,
                    'method'       => "refund",
                ];
                $wechatPay =  Service::submitOrder($params);
                $wechatPay = json_decode($wechatPay,true);
                if($wechatPay["return_code"] == "SUCCESS" && $wechatPay['return_msg'] == "OK"){
                    //退款成功更改订单状态
                    $this->status = self::STATUS_REFUND;
                    $this->save();
                    $payLog->status = PayLog::STATUS_REFUND;
                    $payLog->save();
                }
                break;
            case "alipay":
                exception("不支持支付宝退款");
        }
        switch ($this->pay_type){
            //
            case "admin":
                OrderGoods::where("order_id", $this->id)->update([
                    "status" => self::STATUS_CANCEL
                ]);
                break;
            default:
                OrderGoods::where("order_id", $this->id)->update([
                    "status" => self::STATUS_REFUND
                ]);
        }


    }



    //检测订单是否完成
    public function checkOrderSuccessStatus($order_id){
        $condition = [
            "order.id" => $order_id,
        ];
        $orderInfo = $this->getOrderInfo($condition);

        if($orderInfo['surplus_class_hour'] == 0){
            //如果课时消耗完成 变成 已完成状态
            self::setSuccessStatus($orderInfo['id']);

        }
    }

    public static function setSuccessStatus($order_id){
        self::where("id",$order_id)->update([
            "status" => self::STATUS_SUCCESS
        ]);
        OrderGoods::where("order_id", $order_id)->update([
            "status" => self::STATUS_SUCCESS
        ]);
    }


    /*
     * 停课
     * */
    public function stopOrder($stop_content){
        $this->status = $this::STATUS_STOP;
        $this->stop_content = $stop_content;
        $this->save();
        OrderGoods::where("order_id", $this->id)->update([
            "status" => self::STATUS_STOP
        ]);
    }


    /*
        * 消耗课时
        * */
    public function useHour($msg, $hour){
        if(!is_numeric($hour)){
            exception("请填写数字");
        }

        if(!in_array($this->status, [ self::STATUS_PAY])){
            exception("当前状态不允许消耗课时");
        }
        //执行消耗课时操作
        $orderInfo = $this->getOrderInfo(["order.id" => $this['id']]);
//        dump($orderInfo);exit;
        if($orderInfo['surplus_class_hour']<$hour){
            exception("剩余课时不足");
        }
        $orderGoodsModel = new OrderGoods();
        $orderSignModel = new OrderSign();
        $condition = [
            "order_goods.order_id" => $orderInfo['id'],
        ];
        $orderGoods = $orderGoodsModel->getTimeTable($condition,"",false);
        $orderGoods["class_hour"] = $hour;

        $sign_data[] = $orderSignModel->sign($orderGoods,date("Y-m-d"),OrderSign::STATUS_ADMIN,"",true);
        if(count($sign_data) <= 0){
            exception("请选择学员进行签到");
        }

        $orderSignModel->insertAll($sign_data);


        //检测下订单是否完成
        $order = new Order();
        foreach ($sign_data as $key => $value){
            $order->checkOrderSuccessStatus($value['order_id']);
        }

        //添加日志
        $orderLog = new OrderLog();
        $logData = [
            "order_id" => $this->id,
//            "user_id" => $user["id"],
            "content" => $msg,
        ];

        $orderLog->save($logData);
    }

    public function changeOrderSn(){
        $this->order_sn = PayLog::getOrderSn(PayLog::COURSE_ORDER);
        $this->save();
    }

    public function changeMoney($params,$adminName){
        if($this['type'] != $this::TYPE_ADMIN){
            exception("只有后台录单的才能修改价格呦~");
        }
        if(isset($params['money']) && $this['money'] != $params['money']){
            if($params['money'] > $this['course_price']){
                exception("修改金额不能大于原价");
            }
            $msg = $adminName."修改价格：".$this['money']."->".$params['money'];
            $this->discount_money = $this['discount_money'] + $this['money'] - $params['money'];
            $this->money = $params['money'];
            $this->save();
            //添加日志
            $orderLog = new OrderLog();
            $orderLog->save([
                "order_id" => $this->id,
                "content" => "$msg",
            ]);
        }
    }

    public function changeTeacher($params,$adminName = ''){
        $logData = [];
        foreach ($params as $key => $value){
            $oldOrderGoods = OrderGoods::where("id",$key)->find();
            if($oldOrderGoods['teacher_id'] != $value['teacher_id']){

                $oldTeacherName = User::where("id",$oldOrderGoods['teacher_id'])->value("nickname")??'';

                $teacherName = User::where("id",$value['teacher_id'])->value("nickname")??'';
                $msg = $adminName.$oldOrderGoods['school_name']."-".$oldOrderGoods['classes_name']."-".$oldOrderGoods['time_name']."修改老师：".$oldTeacherName."->".$teacherName;

                $logData[] = [
                    "order_id" => $this->id,
                    "content" => $msg,
                ];
                OrderGoods::where("id",$key)->update(['teacher_id'=>$value['teacher_id']]);
            }

        }
        //添加日志
        if(count($logData)){
            $orderLog = new OrderLog();


            $orderLog->saveAll($logData);
        }

    }
}
